package h0911;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 字符串相加
 * @date 2024/9/11 0:06
 */
public class StringAdd {
    public static void main(String[] args) {
        String s1="112";
        String s2="23";
        String s = addStrings2(s1, s2);
        System.out.println(s);
    }

    public static String addStrings(String num1, String num2) {
        int n = num1.length() > num2.length() ? num1.length() : num2.length();
        StringBuilder res = new StringBuilder();
        int carry = 0;
        for (int i = 0; i <n; i++) {
            int a = num1.length()-i-1 >= 0 ? num1.charAt(num1.length()-i-1) - '0' : 0;
            int b = num2.length()-i-1 >= 0 ? num2.charAt(num2.length()-i-1) - '0' : 0;
            int num = a + b + carry;
            res.append(num % 10);
            carry = num / 10;
        }
        if (carry!=0){
            res.append(carry);
        }
        return res.reverse().toString();
    }

    public static String addStrings2(String num1, String num2) {
        int n = num1.length() > num2.length() ? num1.length() : num2.length();
        StringBuilder res = new StringBuilder();
        int carry = 0;
        int i=num1.length()-1;
        int j=num2.length()-1;
        while (i>=0||j>=0||carry!=0) {
            int a = i >= 0 ? num1.charAt(i) - '0' : 0;
            int b = j >= 0 ? num2.charAt(j) - '0' : 0;
            int num = a + b + carry;
            res.append(num % 10);
            carry = num / 10;
            i--;
            j--;
        }
        return res.reverse().toString();
    }
}
